package com.wenjie.original.flex_config.typehandler;

import com.google.common.collect.Sets;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wenjie
 * @Description 这个是mybaits-flex的类型转换器   进行,分割的字符串和Set<Long>之间的转换            https://mybatis-flex.com/zh/core/column.html#typehandler
 * @date 2024/5/22 14:33
 */
public class SetLongTypeHandler extends BaseTypeHandler<Set<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<Long> parameter, JdbcType jdbcType) throws SQLException {

        if (parameter != null) {
            Set<String> longSet = parameter.stream().map(s -> String.valueOf(s)).collect(Collectors.toSet());
            ps.setString(i, String.join(",", longSet));
        } else {
            ps.setNull(i, jdbcType.TYPE_CODE);
        }
    }

    @Override
    public Set<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return splitByComma(rs.getString(columnName));
    }

    @Override
    public Set<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return splitByComma(rs.getString(columnIndex));
    }

    @Override
    public Set<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return splitByComma(cs.getString(columnIndex));
    }

    private Set<Long> splitByComma(String string) {
        if (string == null || string.isEmpty()) return null;
        return Sets.newHashSet(string.split(",")).stream().map(s -> Long.parseLong(s)).collect(Collectors.toSet());
    }

}
